package com.jboost.modules.app.util;
import com.google.common.collect.Maps;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import org.springframework.http.HttpHeaders;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.UUID;

public class JdyFileUtils {

    public final static ThreadLocal<String> UUIDS = new ThreadLocal<>();


    final static String tokenUrl = "https://api.jiandaoyun.com/api/v5/app/entry/file/get_upload_token";

    public static String upload(String appid,String entryId,String urlString,HttpHeaders headers) throws IOException {
        HashMap<String, Object> map =
                Maps.newHashMap();
        map.put("app_id",appid);
        map.put("entry_id",entryId);
        map.put("transaction_id", UUIDS.get());
        String s = HttpRestUtils.post(tokenUrl, map,headers );
        JdyFile jdyFile = JSONUtil.fromJson(s, JdyFile.class);
        JdyFile.TokenAndUrlListBean tokenAndUrlListBean = jdyFile.getToken_and_url_list().get(0);
        String download = download(urlString);
        File file = new File(download);
        HashMap<String, Object> map1 =
                Maps.newHashMap();
        map1.put("token",tokenAndUrlListBean.getToken());
        map1.put("file",file);
        String s1 = FormDataInterFaceUtils.doPost(tokenAndUrlListBean.getUrl(),map1);
        file.delete();
        return (String) JSONUtil.fromJson(s1,HashMap.class).get("key");

    }

    public static void uploadFile(String targetUrl, String filePath) throws IOException {
        String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
        String CRLF = "\r\n"; // 换行符
        URL url = new URL(targetUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        ) {
            // 发送文件数据
            File file = new File(filePath);
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(CRLF);
            writer.append(CRLF).flush();

            Files.copy(file.toPath(), output);
            output.flush(); // 确保文件数据发送完毕

            writer.append(CRLF).flush(); // 结束行
            writer.append("--" + boundary + "--").append(CRLF);
        }

        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();
        System.out.println("Response Code: " + responseCode);

        connection.disconnect();
    }




//---------------------------------------------------------

    public static String download(String urlString) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            String filename = "/tmp/temp.png";
            File file = new File(filename);
            os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

            return filename;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //从微信下载图片时如果没有id对应的图片则下载一个空图片，不会存在返回为null的情况
        return null;
    }

}
